<template>
	<view class="content">
		<scroll-view
			scroll-y
			class="task-scroll-view"
			@scrolltolower="loadMoreTasks"
			refresher-enabled
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="task-list" v-if="taskList.length > 0">
				<view class="task-item" v-for="task in taskList" :key="task.taskId" @click="goToTaskDetail(task.taskId)">
					<image class="task-image" :src="getFirstImageUrl(task)" mode="contain" @error="imageError(task.taskId, $event)" @load="imageLoad(task.taskId)"></image>
					<view class="job-title-line">{{ task.jobName }}</view>
					<view class="job-info-row">
						<view class="job-info-left">{{ formatJobInfo(task) }}</view>
						<view class="job-info-right"> ¥{{ task.price }}{{ getSalaryUnit(task) }}</view>
					</view>
					<view class="task-info">
						<text class="task-title">{{ task.title }}</text>
					</view>
					<view class="publisher-info">
						<image v-if="task.avatar" class="publisher-avatar" :src="getAvatarUrl(task)" mode="aspectFill" />
						<text class="publisher-nickname">{{ task.nickName || task.userName || '匿名' }}</text>
					</view>
				</view>
			</view>
			<view v-else class="empty-tip">
				<text>暂无任务可显示</text>
			</view>
			<uni-load-more :status="loadMoreStatus"></uni-load-more>
		</scroll-view>
		<!-- 发布弹窗 -->
		<view v-if="showPublishPopup" class="custom-popup-mask" @click="closePublishPopup">
			<view class="custom-popup" @click.stop>
				<view class="popup-item" @click="onChooseAlbum">从相册选择</view>
				<view class="popup-item" @click="onTakePhoto">
					相机
					<text class="popup-desc">拍摄与直播</text>
				</view>
				<view class="popup-item" @click="onTextGenerate">写文字</view>
				<view class="popup-cancel" @click="closePublishPopup">取消</view>
			</view>
		</view>
	</view>
</template>

<script>
import config from '@/config/config.js'
import { mapGetters } from 'vuex'

export default {
	data() {
		return {
			taskList: [],
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				title: null,
				status: 0 // 只显示进行中的任务
			},
			total: 0,
			loading: false,
			loadMoreStatus: 'more', // more | loading | noMore
			showPublishPopup: false,
			isRefreshing: false
		};
	},
	computed: {
		...mapGetters('user', ['userInfo', 'isLogin'])
	},
	onLoad() {
		this.getTaskList();
	},
	onShow() {
		this.showPublishPopup = false;
	},
	mounted() {
		// 监听tabBar中间按钮点击事件
		uni.onTabBarMidButtonTap(() => {
			const pages = getCurrentPages();
			if (pages.length > 0) {
				const currentPage = pages[pages.length - 1];
				console.log('Current page route in home.vue:', currentPage.route);
				if (currentPage.route === 'pages/tabbar/home/home') {
					this.showPublishPopup = true;
				}
			}
		});
	},
	methods: {
		async getTaskList() {
			if (this.loading) return;
			this.loading = true;
			this.loadMoreStatus = 'loading';

			try {
				const token = uni.getStorageSync('token');
				const [err, res] = await uni.request({
					url: `${config.baseUrl}${config.apiPrefix}/system/task/list`,
					method: 'GET',
					header: {
						'Authorization': `Bearer ${token}`
					},
					data: { ...this.queryParams, excludeSelf: true }
				});

				if (err) {
					console.error('获取任务列表失败:', err);
					uni.showToast({
						title: '加载任务失败',
						icon: 'none'
					});
					this.loadMoreStatus = 'more';
					return;
				}

				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					let newTasks = res.data.rows || [];
					this.total = res.data.total;
					this.taskList = this.queryParams.pageNum === 1
						? newTasks
						: this.taskList.concat(newTasks);

					if (this.taskList.length < this.total) {
						this.loadMoreStatus = 'more';
					} else {
						this.loadMoreStatus = 'noMore';
					}
				} else {
					console.error('获取任务列表失败:', res.data.msg || '未知错误');
					uni.showToast({
						title: res.data.msg || '加载任务失败',
						icon: 'none'
					});
					this.loadMoreStatus = 'more';
				}
			} catch (e) {
				console.error('请求任务列表异常:', e);
				uni.showToast({
					title: '加载任务异常',
					icon: 'none'
				});
				this.loadMoreStatus = 'more';
			} finally {
				this.loading = false;
			}
		},
		loadMoreTasks() {
			if (this.loadMoreStatus === 'noMore' || this.loading) return;
			this.queryParams.pageNum++;
			this.getTaskList();
		},
		imageError(taskId, e) {
			// console.error(`任务ID: ${taskId} 图片加载失败:`, e.detail.errMsg);
		},
		imageLoad(taskId) {
			// console.log(`任务ID: ${taskId} 图片加载成功`);
		},
		async toggleLike(task) {
			if (!this.isLogin) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				return;
			}

			uni.showLoading({
				title: '操作中...',
				mask: true
			});

			// console.log('点击前，任务ID:', task.taskId, '当前likeCount:', task.likeCount, 'isLiked:', task.isLiked);

			try {
				const token = uni.getStorageSync('token');
				const [err, res] = await uni.request({
					url: `${config.baseUrl}${config.apiPrefix}/system/task/like/toggle/${task.taskId}`,
					method: 'POST',
					header: {
						'Authorization': `Bearer ${token}`,
						'Content-Type': 'application/json'
					}
				});

				if (err) {
					console.error('切换点赞状态失败:', err);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
					return;
				}

				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					// 更新前端状态
					task.isLiked = !task.isLiked;
					if (res.data.data === 1) { // 1表示点赞成功
						task.likeCount = (task.likeCount || 0) + 1;
						uni.showToast({
							title: '点赞成功',
							icon: 'success'
						});
					} else { // 0表示取消点赞
						task.likeCount = Math.max(0, (task.likeCount || 0) - 1);
						uni.showToast({
							title: '取消点赞成功',
							icon: 'success'
						});
					}
					// console.log('点击后，任务ID:', task.taskId, '更新后likeCount:', task.likeCount, '更新后isLiked:', task.isLiked);
				} else {
					console.error('切换点赞状态失败:', res.data.msg || '未知错误');
					uni.showToast({
						title: res.data.msg || '操作失败',
						icon: 'none'
					});
				}
			} catch (e) {
				console.error('切换点赞状态异常:', e);
				uni.showToast({
					title: '操作异常',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},
		goToTaskDetail(taskId) {
			// 检查当前用户是否为任务发布者
			const currentTask = this.taskList.find(task => task.taskId == taskId);
			if (currentTask && this.userInfo && currentTask.createBy == this.userInfo.userId) {
				// 如果是发布者，跳转到管理页面
				uni.navigateTo({
					url: `/pages/task-manage/task-manage?taskId=${taskId}`
				});
			} else {
				// 如果是普通用户，跳转到详情页面
				uni.navigateTo({
					url: `/pages/task-detail/task-detail?taskId=${taskId}`
				});
			}
		},
		closePublishPopup() {
			this.showPublishPopup = false;
		},
		onChooseAlbum() {
			this.closePublishPopup();
			uni.chooseImage({
				count: 1,
				sourceType: ['album'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					uni.navigateTo({
						url: '/pages/tabbar/publish/publish?image=' + encodeURIComponent(tempFilePath)
					});
				}
			});
		},
		onTakePhoto() {
			this.closePublishPopup();
			uni.chooseImage({
				count: 1,
				sourceType: ['camera'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					uni.navigateTo({
						url: '/pages/tabbar/publish/publish?image=' + encodeURIComponent(tempFilePath)
					});
				}
			});
		},
		onTextGenerate() {
			this.closePublishPopup();
			uni.navigateTo({
				url: '/pages/text-input/text-input'
			});
		},
		getFirstImageUrl(task) {
			if (task.imageUrls) {
				const arr = task.imageUrls.split(',');
				if (arr[0]) {
					// 兼容本地路径和网络路径
					if (/^https?:\/\//.test(arr[0])) {
						return arr[0];
					} else {
						// 拼接baseUrl+apiPrefix
						return config.baseUrl + config.apiPrefix + arr[0];
					}
				}
			}
			// 兼容老数据
			return task.imageUrl || '';
		},
		formatJobInfo(task) {
			const district = task.district || '';
			const salaryType = task.salaryType || '';
			return [district, salaryType].filter(Boolean).join('｜');
		},
		getSalaryUnit(task) {
			// 优先用task.salaryUnit
			if (task.salaryUnit) return task.salaryUnit;
			// 兼容salaryUnitIndex和salaryUnits
			if (typeof task.salaryUnitIndex === 'number' && Array.isArray(task.salaryUnits) && task.salaryUnits[task.salaryUnitIndex]) {
				return task.salaryUnits[task.salaryUnitIndex];
			}
			// 兼容全局salaryUnits
			if (typeof task.salaryUnitIndex === 'number' && this.salaryUnits && this.salaryUnits[task.salaryUnitIndex]) {
				return this.salaryUnits[task.salaryUnitIndex];
			}
			// 兼容字符串salaryUnits
			if (typeof task.salaryUnits === 'string') {
				return task.salaryUnits;
			}
			// 默认值
			return '元/天';
		},
		async onRefresh() {
			this.isRefreshing = true;
			this.queryParams.pageNum = 1;
			const res = await this.getTaskList();
			this.isRefreshing = false;
		},
		getAvatarUrl(task) {
			if (task.avatar) {
				if (/^https?:\/\//.test(task.avatar)) {
					return task.avatar;
				}
				return config.baseUrl + config.apiPrefix + task.avatar;
			}
			return '/static/images/profile.jpg';
		}
	}
};
</script>

<style>
.content {
	padding: 20rpx;
	background-color: #f8f8f8;
	min-height: 100vh;
}

.task-scroll-view {
	height: calc(100vh - 100rpx); /* 减去底部tabbar的高度 */
}

.task-list {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
}

.task-item {
	width: calc(50% - 10rpx);
	margin-bottom: 20rpx;
	background-color: #fff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.task-image {
	width: 100%;
	height: 200rpx;
	background-color: #e0e0e0; /* 添加一个灰色背景色 */
}

.publisher-info {
	display: flex;
	align-items: center;
	padding: 0 12rpx 8rpx 12rpx;
	margin-top: -50rpx;
}

.publisher-avatar {
	width: 40rpx;
	height: 40rpx;
	border-radius: 20rpx;
	margin-right: 10rpx;
	background: #eee;
}

.publisher-nickname {
	font-size: 22rpx;
	color: #888;
}

.job-title-line {
	font-size: 26rpx;
	color: #222;
	text-align: left;
	margin: 10rpx 0 0 12rpx;
	font-weight: bold;
}

.job-info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 4rpx 0 12rpx 0;
	padding: 0 12rpx;
}

.job-info-left {
	font-size: 20rpx;
	color: #007aff;
	font-weight: 500;
}

.job-info-right {
	font-size: 20rpx;
	color: #ff5722;
	font-weight: 500;
}

.task-info {
	padding: 20rpx;
	flex: 1;
}

.task-title {
	font-size: 24rpx;
	font-weight: bold;
	color: #333;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	margin-bottom: 10rpx;
}

.empty-tip {
	text-align: center;
	padding: 50rpx;
	color: #999;
	font-size: 24rpx;
}

.custom-popup-mask {
	position: fixed;
	left: 0; right: 0; top: 0; bottom: 0;
	background: rgba(0,0,0,0.3);
	z-index: 9999;
	display: flex;
	align-items: flex-end;
}
.custom-popup {
	width: 100vw;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	padding-bottom: 40rpx;
}
.popup-item {
	padding: 40rpx 0 20rpx 0;
	text-align: center;
	font-size: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	position: relative;
}
.popup-desc {
	display: block;
	font-size: 20rpx;
	color: #999;
	margin-top: 8rpx;
}
.popup-cancel {
	padding: 40rpx 0 0 0;
	text-align: center;
	font-size: 30rpx;
	color: #007aff;
}
</style>
